from django.shortcuts import render
from django_fsm import can_proceed, transition, RETURN_VALUE, GET_STATE, has_transition_perm
from myOrder.models import BlogPost
from django.shortcuts import render, get_object_or_404
import json
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout

# Create your views here.
def publish_view(request, p_id):
    post = get_object_or_404(BlogPost, pk=p_id)
    print(post.state)
    # print((post.publish))
    # if not can_proceed(post.publish):
    #     return HttpResponse(json.dumps({'state': 10, 'message': 'can not publish'}), content_type="application/json")
    #
    # post.publish()
    # post.save()
    print(request.user)
    if not request.user.is_authenticated():
        print(request.user)
        user = authenticate(username='louis', password='Chen323428')
        login(request, user)

    if not has_transition_perm(post.remove, request.user):
        return HttpResponse(json.dumps({'state': 20, 'message': 'do not have the PermissionDenied'}), content_type="application/json")

    print(post.remove())
    post.save()
    return HttpResponse(json.dumps({'state': 0, 'message': 'have been published'}), content_type="application/json")